<template>
  <div class="app-container">
    <div class="box ph-30">
      <div class="panel">
        <div class="panel-header">
          <h3 class="panel-title">选择运动员</h3>
        </div>
        <div class="panel-body">
          <div class="text-right mb20">
            <el-button type="success" @click="chooseSportman">选择参赛运动员</el-button>
            <el-button type="success" @click="importSportman">批量导入人员</el-button>
            <el-button type="success" @click="addCoach">新增运动员</el-button>
          </div>

          <el-tabs
            v-if="signType=='2'"
            v-model="activeTeam"
            type="card"
            class="demo-tabs"
            @tab-click="teamClick"
          >
            <el-tab-pane v-for="t in teamList" :key="t.id" :label="t.name" :name="t.id" />
          </el-tabs>
          <!-- 已选运动员列表-->
          <div class="hasChoose">
            <el-button plain type="primary" v-for="p in choosedList" @click="signForThisMan(p)">
              {{p.realName}}
              <span v-if="p.sex=='1'">(男)</span>
              <span v-if="p.sex=='0'">(女)</span>
            </el-button>
          </div>
          <el-table :data="signInfoTable" style="width: 100%">
            <el-table-column type="expand" align="center">
              <template #default="props">
                <el-table :data="props.row.signInfo" border>
                  <el-table-column label="序号" width="80px" type="index" align="center" />
                  <el-table-column label="报项">
                    <template #default="scope">
                      {{ scope.row.cptProjectName }}
                      {{ scope.row.cptGroupName }}{{ scope.row.cptLevelName }}{{ scope.row.cptSonLevelName }}
                      {{ scope.row.zu }}
                    </template>
                  </el-table-column>

                  <el-table-column v-if="coachOrLeaderFlag=='1'" label="教练" prop="coachNames" />
                  <el-table-column v-if="coachOrLeaderFlag=='1'" label="领队" prop="leaderNames" />
                  <el-table-column label="操作" fixed="right" width="100" align="center">
                    <template #default="scope">
                      <el-button type="text" @click="editThis(scope.row)">编辑</el-button>
                      <el-button type="text" @click="removeThis(scope.row.id)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="运动员" min-width="120px">
              <template #default="scope">
                <div style="display: flex;align-items: center;">
                  <el-image v-if="scope.row.personInfo.picUrl" style="width: 50px; height: 50px" fit="contain" :src="scope.row.personInfo.picUrl" />
                  <p class="ml10">{{ scope.row.personInfo.realName }}({{ scope.row.personInfo.sexStr }})</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="参赛队">
              <template #default="scope">
                {{ scope.row.signInfo[0]?.groupName }}
              </template>
            </el-table-column>
            <el-table-column v-if="signType=='2'" label="队伍">
              <template #default="scope">
                {{ scope.row.signInfo[0]?.teamName }}
              </template>
            </el-table-column>
            <el-table-column label="证件号" min-width="140px">
              <template #default="scope">
                {{ scope.row.personInfo?.idcTypeStr }}
                <div>{{ scope.row.personInfo?.idcCode }}</div>
              </template>
            </el-table-column>
            <el-table-column label="出生日期" min-width="100px" prop="personInfo.birth" />
            <el-table-column label="国籍">
              <template #default="scope">
                {{ scope.row.personInfo?.countryName }}
              </template>
            </el-table-column>
            <el-table-column label="民族" prop="personInfo.nation" />

            <el-table-column label="联系方式" min-width="100px">
              <template #default="scope">
                {{ scope.row.personInfo?.phone }}
              </template>
            </el-table-column>

            <!--            补充信息-->
            <el-table-column v-for="(e,index) in extraTableHead" :key="index" :label="e">
              <template #default="scope">
                <el-link v-if="scope.row.signInfo[0].extraPersonInfoMapList[index]?.type=='2'" :herf="scope.row.signInfo[0].extraPersonInfoMapList[index].value.url">
                  {{ scope.row.signInfo[0].extraPersonInfoMapList[index].value.name }}
                </el-link>
                <img v-else-if="scope.row.signInfo[0].extraPersonInfoMapList[index]?.type=='3'" style="width: 50px;" :src="scope.row.signInfo[0].extraPersonInfoMapList[index].value.url||scope.row.signInfo[0].extraPersonInfoMapList[index].value">
                <span v-else>{{ scope.row.signInfo[0].extraPersonInfoMapList[index]?.value }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150" align="center">
              <template #default="scope">
                <el-button v-if="extraform&&extraform.length>0" type="text" @click="goPersonInfo(scope.row)">
                  <span v-if="scope.row.extraPersonInfo">修改</span>
                  <span v-else class="red">完善补充信息</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

        </div>
        <div class="panel-footer text-center">
          <el-button type="success" plain round @click="goPrev()">上一步</el-button>
          <el-button type="success" round @click="submitForm()">下一步</el-button>
        </div>
      </div>
    </div>

    <dialogAddCoach ref="dialogAddCoachRef" />
    <dialogSportsmanList ref="dialogSportsmanListRef" @submitForm="getSignInfoList" />
    <dialogAllSportsmanList ref="dialogAllSportsmanListRef" @transfer="getChoosed" @submitForm="getSignInfoList" />

    <dialogImport ref="dialogImportProps" @submitForm="getMySignInfo" />

    <el-dialog v-model="showResult" :close-on-click-modal="false" :show-close="false">
      <el-result icon="success" title="报名成功">
        <template #extra>
          <el-button type="primary" @click="downloadVoucher">下载凭证</el-button>
          <el-button type="primary" @click="goMySign">查看报项</el-button>
        </template>
      </el-result>

    </el-dialog>

    <dialogChangeCoach ref="popChangeCoach" @submitForm="getMySignInfo" />

    <dialogExtraForm ref="popExtraForm" @submitForm="getSignInfoList" />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import * as match from '@/api/match/pc'
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import dialogAddCoach from './components/addCoach'
import dialogSportsmanList from './components/sportsmanList'
import dialogAllSportsmanList from './components/allSportsmanList'
import dialogImport from './components/import'
import dialogChangeCoach from './components/changeCoach'
import dialogExtraForm from './components/extraForm'
const { proxy } = getCurrentInstance()
const router = useRouter()
const route = useRoute()
import _ from 'lodash'
import { ElMessage, ElMessageBox } from 'element-plus'
const data = reactive({
  coachForm: {},
  tableData: [], signInfoTable: [],choosedList:[],
  extraPersonInfoMapList: [],
  teamList: [],
  extraform: [],
  groupId: '0',
  signType: '',
  coachOrLeaderFlag: null,
  noPhotoCanSign: null,
  showResult: false,
  showExtraForm: false,
  extraTableHead: [],
  activeTeam: ''
})
const { activeTeam, tableData, signInfoTable, choosedList,showExtraForm, extraPersonInfoMapList, teamList, extraform, groupId, signType, coachOrLeaderFlag, showResult, noPhotoCanSign, extraTableHead, coachForm } = toRefs(data)
let matchId = ''
let signInfoType = null
onMounted(() => {
  groupId.value = route.query.groupId
  signType.value = route.query.signType
  matchId = route.query.matchId
  if (signType.value == '2') {
    // 团队-队伍报名-获取队伍
    getTeamList(matchId, groupId.value)
  } else {
    getSignInfoList()
  }
  getMatch(matchId)
  getTableHead()
  getMySignInfo()
})
let chargeFlag
function getMatch(id) {
  match.getMatchById({
    id: id
  }).then(res => {
    chargeFlag = res.data.chargeFlag
    noPhotoCanSign.value = res.data.noPhotoCanSign
    coachOrLeaderFlag.value = res.data.coachOrLeaderFlag
    extraform.value = JSON.parse(res.data.participantsInfo)
  })
}
function getMySignInfo() {
  // 获取已报
  match.getMySignInfo({
    cptId: matchId,
    groupId: groupId.value
  }).then(res => {
    tableData.value = res.data.signInfo
    signInfoType = res.data.type
  })
}
function getSignInfoList() {
  // console.log(activeTeam.value)
  match.getMySignInfoList({
    cptId: matchId,
    groupId: groupId.value,
    teamId: activeTeam.value || ''
  }).then(res => {
    signInfoTable.value = res.data
    if(signInfoTable.value.length>0){
      let choosedIds = []
      for(let p of choosedList.value){
        choosedIds.push(p.id)
      }
      for(var pp of signInfoTable.value){
        if(choosedIds.indexOf(pp.personInfo.id)==-1){
          // 判断是否已存在
          choosedList.value.push(pp.personInfo)
        }
      }
    }
  })
}
function getTableHead() {
  match.getCptExtraInfo(matchId).then(res => {
    // console.log(res.data)
    extraTableHead.value = res.data
  })
}
function getTeamList(a, b) {
  match.getMyTeamList(a, b).then(res => {
    teamList.value = res.data
    activeTeam.value = teamList.value[0].id
    getSignInfoList()
  })
}
function teamClick(tab, event) {
  activeTeam.value = tab.props.name
  getSignInfoList()
}
function submitForm() {
  if (signInfoType == '1') {
    ElMessageBox.confirm('已报项，前往我的报项', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push({ name: 'myMatch' })
    })
    return
  }
  if (extraform.value && extraform.value.length > 0) {
    let needBuchong = false
    for (const e of extraform.value) {
      if (e.status == '0') {
        needBuchong = true
      }
    }
    for (const s of signInfoTable.value) {
      if (s.extraPersonInfo == null && needBuchong) {
        ElMessage.error('请完善运动员补充信息')
        return
      }
    }
  }
  if (signInfoType == '2') {
    match.recoverMySign({ cptId: matchId, groupId: groupId.value }).then(res => {
      if (res.msg.indexOf('Exception:') > -1) {
        const msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      } else {
        afterRecover()
      }
    })
  } else {
    afterRecover()
  }
}
function afterRecover() {
  if (signInfoTable.value.length == 0) {
    ElMessage.error('请至少选择一个项目')
    return
  }
  // 判断是否收费
  if (chargeFlag == '0') {
    var obj = {
      cptId: matchId,
      groupId: groupId.value
    }
    match.commitSign(obj).then(res => {
      console.log(res.data)
      showResult.value = true
    })
  } else {
    // 生成账单
    router.push({
      name: 'expenseDetails',
      query: {
        matchId: matchId,
        groupId: groupId.value
      }
    })
  }
}

function goPrev() {
  router.go(-1)
}
function chooseSportman() {
  if (signInfoType == '2') {
    match.recoverMySign({
      cptId: matchId,
      groupId: groupId.value
    }).then(res => {
      if (res.msg.indexOf("Exception:") > -1) {
        let msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      }
      getMySignInfo()
    })
  }

  const params = {
    title: '选择运动员',
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value,
    choosedList: choosedList.value
  }
  proxy.$refs['dialogAllSportsmanListRef'].open(params)
}
function getChoosed(list) {
  choosedList.value = list
}

function addCoach() {
  if (signInfoType == '2') {
    match.recoverMySign({
      cptId: matchId,
      groupId: groupId.value
    }).then(res => {
      if (res.msg.indexOf("Exception:") > -1) {
        let msg = res.msg.slice(10)
        ElMessageBox.confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('用户点击确定')
        })
        return
      }
      getMySignInfo()
    })
  }
  const params = {
    title: '新增运动员',
    id: 0,
    groupId: groupId.value
  }
  proxy.$refs['dialogAddCoachRef'].open(params)
}
function signForThisMan(p) {
  const params = {
    title: '选择报项',
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value,
    personal: p,
    choosedList: choosedList.value
  }
  proxy.$refs['dialogSportsmanListRef'].open(params)

}
function editThis(row) {
  const params = {
    title: '修改报项',
    personal: row.cptPersonInfo,
    matchId: matchId,
    groupId: groupId.value,
    rankId: activeTeam.value,
    signType: signType.value,
    noPhotoCanSign: noPhotoCanSign.value,
    coachOrLeaderFlag: coachOrLeaderFlag.value
  }
  proxy.$refs['dialogSportsmanListRef'].open(params)
}
function removeThis(id) {
  ElMessageBox.confirm('确定移除这条报项吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    match.deleteSign(id).then(res => {
      // 重新获取已报名信息
      ElMessage.success('已移除该报项')
      getSignInfoList()
    })
  })
}
function changeCoach(cptId, groupId) {
  // 更换教练
  const params = {
    title: '修改教练',
    groupId: groupId,
    cptId: cptId
  }
  proxy.$refs['popChangeCoach'].open(params)
}
function importSportman() {
  const params = {
    title: '批量导入人员',
    groupId: groupId.value
  }
  proxy.$refs['dialogImportProps'].open(params)
}
function goMySign() {
  router.push({
    name: 'myMatch'
  })
}

const goPersonInfo = (row) => {
  if (signInfoType == '1') {
    ElMessageBox.alert('已报项，前往我的报项', '提示', {
      confirmButtonText: 'OK',
      callback: (Action) => {
        router.push({ name: 'myMatch' })
      }
    })
    return
  }
  // 完善补充信息
  console.log(row)
  const params = {
    title: '完善补充信息',
    participantsInfoArr: extraform.value,
    personId: row.personInfo.id,
    extraId: row.extraPersonInfo?.id || 0
  }
  proxy.$refs['popExtraForm'].open(params)
}
function downloadVoucher() {
  // 下载凭证
  proxy.download(
      `/pdf/getPayedOrderPdf/${matchId}/${groupId.value||0}`,{},'报项凭证.pdf'
  )
}
</script>

<style scoped lang="scss">
	.app-container{ padding: 0;background: #F5F7F9;}
	.panel-footer .el-button--success{background: linear-gradient(270deg, #39DBA7, #38EF7D);border: none;
		padding: 0 40px;
		font-size: 16px;
	}
	.panel-footer .el-button--success.is-plain{background: #fff;border:1px solid #2ED981;color: #2ED981;}
	.hasChoose{margin: 0 0 20px;}
  .chooseForm{
		:deep(.el-form-item__content){background: rgba(245, 247, 249, 0.38);padding: 20px 40px 10px;}
		.el-checkbox{height: auto;}
		:deep(.el-checkbox__input){position: absolute;right: 0;top: 0;}
		.name{text-align: center;}
	}
</style>
